package com.dys.hejiayuncommunity.framework.security.handler;

import com.alibaba.fastjson.JSON;
import com.dys.hejiayuncommunity.common.core.domain.BaseResponse;
import com.dys.hejiayuncommunity.common.utils.ServletUtils;
import com.dys.hejiayuncommunity.system.domain.LoginUser;
import com.dys.hejiayuncommunity.system.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author: 疾风
 * @ClassName: LogoutSuccessHandlerImpl
 * @Description: 自定义登出成功处理类
 * @CreateDate: 2024/12/25
 * @Version: v1.0.0
 */
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Autowired
    private TokenService tokenService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (!Objects.isNull(loginUser)) {
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
        }
        ServletUtils.renderString(response, JSON.toJSONString(BaseResponse.success("登出成功")));
    }
}
